import express from 'express';
// import cookieParser from 'cookie-parser'; // 引入cookie插件
import bodyParser from 'body-parser';
import createError from 'http-errors';
import path from 'path';
import logger from 'morgan';
import router from './router';
import Config from '../config/config.config';
const app = express();

app.use((req, res, next) => {
  console.log(Config.appNameC + '用户访问接口：', new Date(), req.url)
  // 所有方法执行前进行的操作
  res.header("Access-Control-Allow-Origin", req.headers.origin); // 跨域请求域名+端口号
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'content-type, token');
  res.header("Content-Type", "application/json; charset=utf-8");
  res.header("Access-Control-Expose-Headers", "token");
  res.header('Access-Control-Allow-Credentials', true);
  next();
})

// app.use(cookieParser('Ef2HTEWR132')); // cookie操作

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 加入POST支持
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

router(app)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.log('errerrerr:', err)
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
